//
//  ST_RecommendVideoDataAdapter.swift
//  btvideo
//
//  Created by mac on 2020/6/8.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON
import SwiftyUserDefaults
import SwifterSwift



class ST_RecommendVideoDataAdapter: NSObject {

    static let shared = ST_RecommendVideoDataAdapter()
    
    private override init() {
        super.init()
        
         NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUp, object: nil)
                
    }
    
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
//        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController else{
            return
        }
        
        if vc is ST_RecommendPecVideoController{
            return
        }
        
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard self.modify(isThumbUp: isThumbUp, groupId: id) != nil else{
            return
        }
        
        index_delegate?.refreshCell?(groupId: id)
        
        video_detail_delegate?.refreshCell?(groupId: id)
    }
//    MARK: - private Set Properties
    
    private(set) var data_array = [ST_ShowTraitCellModel]()
    
    private(set) var currentPage = 0
    
    
//    MARK: - Public Properties
    
    weak var index_delegate:ST_PinterestHomeDataAdapterViewDelegate?
    
    weak var video_detail_delegate:ST_PinterestHomeDataAdapterViewDelegate?
    
    
    var curr_play_video_index:Int?{
        didSet{
            
            guard let idx = curr_play_video_index else { return }
//            ex: 7  - 2 = 5
            let offSetIdx = data_array.count - idx
            if offSetIdx < 5 {
                
                print("视频 加载更多")
                
                load_data_from_remote()
            }
            
            
        }
    }
    
    var curr_selected_index:Int?
//    MARK: - Public Method
    func modify(isThumbUp:Bool,groupId:String) -> Int? {
        
        guard let idx = self.data_array.firstIndex(where: {$0.group_id.string == groupId}) else{
            return nil
        }
        
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isThumbUp = isThumbUp
        
        if isThumbUp{
            data_array[safe: index]?.thumbUpCount += 1
        }else{
            data_array[safe: index]?.thumbUpCount -= 1
        }
        
        return index
    }
    
    
    func clear_data(){
        
        
        currentPage = 0
        
        self.data_array.removeAll()
        
        
        index_delegate?.reload_view_from_data_adapter(currentCount: 0)
        
        video_detail_delegate?.reload_view_from_data_adapter(currentCount: 0)
        
        
    }
    
    func refresh_data(){
        
        clear_data()
        
        reloadData()
    }
    
    
    func reloadData()  {
        
        currentPage = 0
        
        load_data_from_remote()
    }
    
    fileprivate var loading = false
    
    func load_data_from_remote()  {
        
        
        if loading{
            return
        }
        
        loading = true
        
        currentPage += 1
        
        var param = ["page":currentPage,
                    "size":20] as [String : Any]
        
        
        
//        print("推荐视频参数传递:",param)
        

        JVrequest(PH.recommendVideoApi,parameters:param, success: { (json) in
                    
            
            let list = json["data"]["list"].arrayValue
            
            print("推荐视频数据据：",list,"=======END")
            
            let aArray = list.map { (itemJson) -> ST_ShowTraitCellModel in
                let m = ST_ShowTraitCellModel.init(json: itemJson)
                m.create_view_model_set(maxContentHeight: ST_ShowTraitCell.two_line_max_height)
                return m
            }
            
            
//            aArray.forEach { (videoItem) in
//
//                ST_BTVideoBarrageAdapter.shared.add_will_req(groupId: videoItem.group_id.string)
//
//            }
            
            if self.currentPage == 1{
                self.data_array = aArray
            }else{
                self.data_array += aArray
            }
            
            
            var addedDict = [String: Bool]()

            self.data_array = self.data_array.filter {
                addedDict.updateValue(true, forKey: $0.group_id.string) == nil
            }
            
            self.index_delegate?.reload_view_from_data_adapter(currentCount: aArray.count)
            
            self.video_detail_delegate?.reload_view_from_data_adapter(currentCount: aArray.count)
            
            self.loading = false
            
        }) { (code, err) in
            
            
            self.index_delegate?.fail_load_data(code: code, error: err)
            self.video_detail_delegate?.fail_load_data(code: code, error: err)

            self.loading = false
            
        }
        
        
        
    }
    
    
    

}

